<template>
  <div class="title"></div>
  <div class="login-page">
    <div class="logo-container">
      <img src="@/assets/logo.png" alt="Logo" class="logo">
      <p class="text">医疗保险欺诈监测</p>
    </div>
    <div class="bg"></div>
    <div class="logo"></div>
    <el-row class="form-container">
      <el-col :span="12" class="form">
        <el-form
          :model="formModel"
          :rules="rules"
          ref="form"
          size="large"
          autocomplete="off"
          v-if="isRegister"
        >
          <el-form-item>
            <h1 class="zhuce">注册</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input class="item"
              v-model="formModel.username"
              :prefix-icon="User"
              placeholder="请输入用户名" 
            ></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input class="item"
              v-model="formModel.email"
              :prefix-icon="Message"
              placeholder="请输入邮箱"
            ></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input class="item"
              v-model="formModel.phone"
              :prefix-icon="Phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input class="item"
              v-model="formModel.password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="repassword">
            <el-input class="item"
              v-model="formModel.repassword"
              :prefix-icon="Lock"
              type="password"
              placeholder="请再次输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="register"
              class="button"
              type="primary"
              auto-insert-space
            >
              注册
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = false" class="back">
              返回
            </el-link>
          </el-form-item>
        </el-form>

        <el-form
          :model="formModel"
          :rules="rules"
          ref="form"
          size="large"
          autocomplete="off"
          v-else
        >
          <el-form-item>
            <h1 class="login">登录</h1>
          </el-form-item>

          <el-form-item>
            <el-radio-group v-model="selectedLoginMethod">
              <el-radio label="usernamePassword" class="usernamePassword"
                >用户名密码</el-radio
              >
              <el-radio label="emailVerification" class="emailVerification"
                >邮箱验证码</el-radio
              >
              <el-radio label="phoneVerification" class="phoneVerification"
                >手机号验证码</el-radio
              >
            </el-radio-group>
          </el-form-item>

          <template v-if="selectedLoginMethod === 'usernamePassword'">
            <el-form-item prop="username">
              <el-input
                v-model="formModel.username"
                :prefix-icon="User"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="formModel.password"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
              ></el-input>
            </el-form-item>
          </template>

          <template v-if="selectedLoginMethod === 'emailVerification'">
            <el-form-item prop="email">
              <el-input
                v-model="formModel.email"
                :prefix-icon="Message"
                placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="sendVerificationCode('email')">发送验证码</el-button>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <el-input
                v-model="formModel.verificationCode"
                placeholder="请输入验证码"
                class="verificationCode"
              ></el-input>
            </el-form-item>
          </template>

          <template v-if="selectedLoginMethod === 'phoneVerification'">
            <el-form-item prop="phone">
              <el-input
                v-model="formModel.phone"
                :prefix-icon="Phone"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="sendVerificationCode('phone')">发送验证码</el-button>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <el-input
                v-model="formModel.verificationCode"
                placeholder="请输入验证码"
                class="verificationCode"
              ></el-input>
            </el-form-item>
          </template>

          <el-form-item class="flex">
            <el-checkbox class="remenber">记住我</el-checkbox>
            <el-link type="primary" :underline="false" class="forget"
              >忘记密码?</el-link
            >
          </el-form-item>
          <el-form-item>
            <el-button
              @click="login"
              class="button"
              type="primary"
              auto-insert-space
            >
              登录
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link
              type="info"
              :underline="false"
              @click="isRegister = true"
              class="register"
            >
              注册
            </el-link>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {
  userRegisterService,
  userLoginService
  //sendVerificationCodeService
} from '@/api/user.js'
import userUserStore from '@/stores/user'
import { useRouter } from 'vue-router'
import { User, Lock, Message, Phone } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'

const isRegister = ref(true)
const selectedLoginMethod = ref('usernamePassword') // default login method
const form = ref()
const formModel = ref({
  username: '',
  password: '',
  repassword: '',
  email: '',
  phone: '',
  verificationCode: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位非空',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const register = async () => {
  await form.value.validate()
  await userRegisterService(formModel.value)
  alert('注册成功')
  isRegister.value = false
}

const userStore = userUserStore()
const router = useRouter()

const login = async () => {
  await form.value.validate()
  let loginData = {}
  switch (selectedLoginMethod.value) {
    case 'usernamePassword':
      loginData = {
        username: formModel.value.username,
        password: formModel.value.password
      }
      break
    case 'emailVerification':
      loginData = {
        email: formModel.value.email,
        verificationCode: formModel.value.verificationCode
      }
      break
    case 'phoneVerification':
      loginData = {
        phone: formModel.value.phone,
        verificationCode: formModel.value.verificationCode
      }
      break
  }
  const res = await userLoginService(loginData)
  if (res.data && res.data.token) {
    userStore.setToken(res.data.token)
    ElMessage.success('登录成功')
    router.push('/')
  } else {
    console.error('Token not found in response:', res)
    ElMessage.error('登录失败，请重试。')
  }
}

const sendVerificationCode = async (method) => {
  if (method === 'email' && formModel.value.email) {
    await sendVerificationCodeService({ email: formModel.value.email })
    ElMessage.success('验证码已发送到您的邮箱')
  } else if (method === 'phone' && formModel.value.phone) {
    await sendVerificationCodeService({ phone: formModel.value.phone })


    ElMessage.success('验证码已发送到您的手机')
  } else {
    ElMessage.error('请输入有效的邮箱或手机号')
  }
}
</script>

<style>
.usernamePassword,
.emailVerification,
.phoneVerification {
  position:relative;
  margin-top:-28px;
  font-size:12px;
  color: #000; /* Default color */
}

.el-radio.is-checked .el-radio__label {
  color: rgb(0, 136, 255) !important; /* Change this to the desired color when selected */
}

html, body {
  height: 100%;
  margin: 0;
}

.remenber {
  font-size: 12px;
  color:#000;
  position: relative;
  margin-top:-25px;
}
.forget {
  color: #000;
  position: relative;
  left: 230px;
  margin-top:-25px;
}

.login-page {
  height: 100vh;
  background: url('@/assets/login.jpg') no-repeat center center/cover;
  background-color: #fff;
  position: relative;

  .form-container {
    position: relative;
    margin-top:-200px;
    z-index: 2;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form {
    max-width: 400px;
    width: 120%;
    padding: 20px;
    height: 400px;
    border-radius: 10px;
    margin-right: -970px;
    position: relative;
    color: #111010;
    font-family: 'MedievalSharp', cursive;
    background-color: #fff; /* Set the background color to white */

    .title {
      margin: 0 auto;
      color: #ffd700;
    }
    .button {
      width: 100%;
      background-color: #15a6e4;
      border-color: #ffffff;
      position:relative;
      margin-top:-9px;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
      .el-input {
        margin-bottom: 20px;
        input {
          background-color: rgba(255, 255, 255, 0.8);
          color: #000;
        }
      }
    }
  }
}

.title {
  position: absolute;
  top: 420px;
  left: 135px;
  width: 80%;
  text-align: center;
  z-index: 3;
}

.title h1 {
  font-size: 42px;
  color: #fbfbfb;
  font-family: 'Arial', sans-serif;
  line-height: 1.5;
  margin: 0;
  padding: 10px;
}


.register {
  color: #000;
  font-size: 18.5px;
  position: relative;
  left:-3px;
  margin-top: -15px;
}

.verificationCode {
  width: 245px;
  position: relative;
  left: 115px;
  margin-top: -84px;
}
.login{
  position:relative;
  margin-top: -2px;
}
.item{
  position:relative;
  margin-top:-8px;
}
.zhuce{
  position:relative;
  margin-top: -12px;
}
.back{
  color:#000;
  font-size:15px;
  margin-top:-5px;
  left:-7px;
}
.logo{
  max-width:130px;
  max-height:130px;
  height:auto;
  margin-top:33px;
  left:45px;
  position:relative;
}
.text{
  font-size:18px;
  font-family:Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
  position: relative;
  left:30px;
  margin-top:-5px;

}
</style>